import { useState } from "react"
import { message } from "antd"
import {
  getRoleList,
  updateRole,
  createRole,
  deleteRole
} from "api/system/role"

import { IModalProps } from "app/interfaces/system"

interface IForm {
  roleId: string
  roleKey: string
  roleName: string
  roleSort: number
  status: string
  deptIds: never[]
  deptCheckStrictly: boolean
  menuIds: never[]
  menuCheckStrictly: boolean
}

export interface IEditProps extends IModalProps<IForm> {
  submitForm: (params: IForm) => void
}

export function useRole() {
  const initForm = {
    roleId: "",
    roleKey: "",
    roleName: "",
    roleSort: 0,
    status: "",
    deptIds: [],
    deptCheckStrictly: false,
    menuIds: [],
    menuCheckStrictly: true
  }

  const [total, setTotal] = useState(0)
  const [loading, setLoading] = useState(false)
  const [dataSource, setDataSource] = useState([])
  const [selectedRowKeys, setSelectedRowKeys] = useState([])
  const [queryParams, setQueryParams] = useState({
    roleName: "",
    roleKey: "",
    status: null,
    beginTime: "",
    endTime: "",
    pageNum: 1,
    pageSize: 10
  })

  const [form, setForm] = useState<IForm>(initForm)
  const [modalConfig, setModalConfig] = useState({ title: "", visible: false })

  const getList = async () => {
    try {
      setLoading(true)
      const { code, data } = await getRoleList(queryParams)
      if (code === 200) {
        setDataSource(data.rows)
        setTotal(data.total)
      }
      setLoading(false)
    } catch (e) {
      console.log(e)
      setLoading(false)
    }
  }

  const submitForm = async (params) => {
    try {
      const service = params.postId ? updateRole : createRole
      const { code } = await service(params)
      if (code === 200) {
        setModalConfig({ ...modalConfig, visible: false })
        message.success("操作成功")
        await getList()
      }
    } catch (e) {
      console.log(e)
    }
  }

  const handleDelete = async (ids) => {
    try {
      const { code } = await deleteRole({ ids })
      if (code === 200) {
        message.success("删除成功")
        await getList()
      }
    } catch (e) {
      console.log(e)
    }
  }

  return {
    getList,
    submitForm,
    handleDelete,
    loading,
    total,
    dataSource,
    selectedRowKeys,
    setSelectedRowKeys,
    queryParams,
    setQueryParams,
    form,
    setForm,
    initForm,
    modalConfig,
    setModalConfig
  }
}
